package mbsl.system;

import java.util.ResourceBundle;

/**
 * A simple wrapper for ResourceBundle.
 * <p>
 * It is assumed, if using the prefix functionality, that keys have a dot-qualified name, like <b>database.error</b> or <b>ui.options.showHiddenFiles</b>.
 */
public class TextProvider {
	/**
	 * Creates a TextProvider using the default bundle
	 */
	public TextProvider() {
		this(DEFAULT_RESOURCE_NAME);
	}
	private TextProvider(ResourceBundle pBundle, String pPrefix) {
		mBundle = pBundle;
		mPrefix = pPrefix;
	}
	/**
	 * Creates a TextProvider using the named bundle
	 */
	public TextProvider(String pBundleName) {
		mBundle = ResourceBundle.getBundle(pBundleName);
	}
	/**
	 * Returns the String with the provided key.
	 */
	public String get(String pKey) {
		if (mPrefix == null)
			return mBundle.getString(pKey);
		else
			return mBundle.getString(mPrefix + "." + pKey);
	}
	/**
	 * Creates a new TextProvider with a set prefix.  It uses the same bundle as the TextProvider which spawns it.
	 * <p>
	 * Using this method on a TextProvider that already has a prefix gives the same result as using it on one that doesn't.
	 * It is assumed that keys have a dot-qualified name, like <b>database.error</b> or <b>ui.options.showHiddenFiles</b>.
	 * It is not necessary to include a dot at the end.
	 * Pass <i>null</i> to clear.
	 */
	public TextProvider prefix(String pPrefix) {
		String prefix;
		
		if (pPrefix.endsWith("."))
			prefix = pPrefix.substring(0, pPrefix.length() - 2);
		else
			prefix = pPrefix;
		
		return new TextProvider(mBundle, prefix);
	}
	/**
	 * Returns the set prefix, or null if none is set.
	 */
	public String getPrefix() {
		return mPrefix;
	}
	
	private final static String DEFAULT_RESOURCE_NAME = "text";
	
	private String mPrefix;
	private ResourceBundle mBundle;
}
